<?php
namespace Seller\Controller;
use Common\Model\AgentModel;
use Think\AjaxPage;
use Think\Controller;

class AgentController extends CommonController
{
    public function _initialize()
    {
        $params = array('searchisset' ,'closed' ,'for_audit' ,'searchagent'
        ,"ajax_agent_list","ajax_change_list","rank","add_rank","rank_del",
            "edit_rank","batchdo","edit_agent","audit_up","add_agent","set_rank",
           "edit_agent_rank","searchagent","money_edit","ajax_up_list","agent_view"
        ,"to_member");
        parent::_initialize($params);
    }

    // 代理列表
    public function index()
    {
        $this->display();
    }

    // 已关代理列表
    public function closed()
    {
        $agent_d = D("AgentView");

        $where["agent.u_status"] = array("eq" ,0);
        if(isset($_REQUEST['mName']))
        {
            $mName = trim(I('mName'));
            if($mName != ''){
                $cWhere['agent.agent_name'] = array("like" ,"%$mName%");
                $cWhere['agent.mobile'] = array("like" ,$mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }
        $count = $agent_d->where($where)->count();
        $page = set_page($count, C('PAGE_NUM'));
        $agents = $agent_d->where($where)->limit($page->firstRow.','.$page->listRows)
            ->order('reg_time DESC')->select();

        $this->ranks = M("agent_rank")->where("rank_status = 1")->order("rank_grade ASC")->select();
        $show = $page->show();
        $this->assign('page',$show);
        $this->assign('agents',$agents);
        $this->display();
    }

    // 未审代理
    public function for_audit()
    {
        $agent_d = D("AgentView");
        $where["agent.u_status"] = array("eq" ,2);
        if(isset($_REQUEST['mName']))
        {
            $mName = trim(I('mName'));
            if($mName != ''){
                $cWhere['agent.agent_name'] = array("like" ,"%$mName%");
                $cWhere['agent_info.mobile'] = array("like" ,$mName);
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }

        $count = $agent_d->where($where)->count();
        $page = set_page($count, C('PAGE_NUM'));
        $agents = $agent_d->where($where)->limit($page->firstRow.','.$page->listRows)
            ->order('reg_time DESC')->select();

        $this->ranks = M("agent_rank")->where("rank_status = 1")->order("rank_grade ASC")->select();
        $show = $page->show();
        $this->assign('page',$show);
        $this->assign('agents',$agents);
        $this->display();
    }

    // 代理关闭
    public function closeAgent()
    {
        if(IS_AJAX){
            $agent_id = to_int(I("post.agent_id"));
            $agent = M("agent")->where("agent_id = $agent_id")->find();
            if(!$agent){
                $this->ajaxReturn(array("status" => 'error' ,'msg' => '参数错误'));
            }
            $rs = M("agent")->where("agent_id = $agent_id")->save(array('u_status' => 0));
            if($rs !== false){
                $this->ajaxReturn(array("status" => 'success'));
            }else{
                $this->ajaxReturn(array("status" => 'error' ,'msg' => '关闭失败'));
            }
        }else{
            exit("error");
        }
    }

    // 代理等级
    public function rank()
    {
        $brand_id = to_int(I("get.id"));
        $ranks = M('agent_rank')->where("rank_status = 1 AND brand_id = $brand_id")
            ->order('rank_grade ASC')->select();
        $this->assign('ranks',$ranks);
        $this->assign('brand_id',$brand_id);
        $this->display();

    }

    // 代理级别添加
    public function add_rank()
    {
        if(IS_POST)
        {
            $brand_id = to_int(I("post.brand_id"));
            $rank_name = trim(I("post.rank_name"));
            $welfare = trim(I("post.welfare"));
            // 查询最后一个级别
            $rank_grade = M("agent_rank")->where("rank_status = 1 AND brand_id = $brand_id")->order("rank_grade DESC")->find();
            $rs = M("agent_rank")->add(array(
                'rank_name' => $rank_name,
                'parent_id' => $rank_grade["rank_id"] ? $rank_grade["rank_id"] : 0,
                'welfare' => $welfare,
                'brand_id' => $brand_id,
                'rank_grade' => $rank_grade["rank_grade"] ? $rank_grade["rank_grade"] + 1 : 0
            ));
            if($rs !== false){
                $this->success("添加成功" ,$_SERVER['HTTP_REFERER'] ,1);
            }else{
                $this->error("添加失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $brand_id = to_int(I("get.id"));
            $res = M('agent_rank')->where("rank_status = 1 AND brand_id = $brand_id")->order('rank_grade ASC')->select();
            $this->ranks = M('agent_rank')->where("rank_status = 1 AND brand_id = $brand_id")->order('rank_grade ASC')->select();
            $this->assign("brand_id" , $brand_id);
            $this->display();
        }
    }

    // 代理层级删除
    public function rank_del()
    {
        if(IS_POST)
        {
            $rank_id = to_int(I("post.rank_id"));
            if($rank_id == 1){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "最高层级不可删除"));
            }
            $agents = M("agent_brand")->where("rank_id = $rank_id")->count();
            if($agents > 0){
                $rs["status"] = "error";
                $rs["msg"] = "该层级有代理，不可删";
            }else{
                M('agent_rank')->where("rank_id = $rank_id")->save(array('rank_status' => 0));
                update_rank( $rank_id); // 删除一个层级需更新整个层级架构
                $rs["status"] = "success";
            }
            $this->ajaxReturn($rs);
        }else{
            exit("error");
        }
    }

    // 代理层级编辑
    public function edit_rank()
    {
        if(IS_POST)
        {
            $rank_id = to_int(I("post.rank_id"));
            $rank_name = trim(I("post.rank_name"));
            $welfare = trim(I("post.welfare"));
            if (empty($rank_name)) {
                $this->error('请填写等级名称!');
            }
            M('agent_rank')->where("rank_id = $rank_id")->save(array('rank_name' => $rank_name,'welfare' => $welfare));
            $this->success("修改成功" ,$_SERVER['HTTP_REFERER'] ,1);
        }else{
            $rank_id = to_int(I("get.id"));
            $rank = M('agent_rank')->where("rank_status = 1 AND rank_id = $rank_id")->find();
            if(!$rank){
                $this->success("请求失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            if($rank['parent_id'] == 0){
                $rank["p_name"] = "顶级代理";
            }else{
                $rank["p_name"] = M('agent_rank')->where("rank_id = ".$rank['parent_id'])->getField("rank_name");
            }
            $this->rank = $rank;
            $this->display();
        }
    }

    // 搜索代理是否已存在
    public function searchIsset()
    {
        if(IS_AJAX){
            $skey = trim(I("post.skey"));
            if($skey == "") $this->ajaxReturn(array("status" => 'error' ,'msg' => '请填写手机号'));
            if(!is_mobile($skey)) $this->ajaxReturn(array("status" => 'error' ,'msg' => '手机号格式有误'));
            $where["mobile"] = array("eq" ,$skey);
            $where['shop_id'] = session('shop_id');
            $agent = M("agent")->where($where)->find();
            if($agent){
                $this->ajaxReturn(array("status" => 'error' ,'msg' => '已存在的手机号'));
            }
            $this->ajaxReturn(array("status" => 'success'));
        }else{
            exit("error");
        }
    }

    // 批量关闭代理
    public function batchDo()
    {
        if(IS_POST){
            $do_type = I("post.type");
            $agent_ids = I("post.agent_id");
            if(!is_array($agent_ids) || empty($agent_ids)){
                $this->error("参数有误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            foreach($agent_ids as $id){
                if(!_int($id)){
                    $this->error("参数有误" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                $ids[] = $id;
            }
            $where["agent_id"] = array("in" ,implode("," ,$ids));
            // 批量开启
            if($do_type == 'open'){
                $rs = M("agent")->where($where)->save(array("u_status" => 1));
                if($rs !== false){
                    $this->success("操作成功" ,$_SERVER['HTTP_REFERER'] ,1);
                }else{
                    $this->error("操作失败" ,$_SERVER['HTTP_REFERER'] ,1);
                }
            }
            // 批量关闭
            if($do_type == 'close'){
                $rs = M("agent")->where($where)->save(array("u_status" => 0));
                if($rs !== false){
                    $this->success("操作成功" ,$_SERVER['HTTP_REFERER'] ,1);
                }else{
                    $this->error("操作失败" ,$_SERVER['HTTP_REFERER'] ,1);
                }
            }
        }else{
            exit("error");
        }
    }

    // 代理审核
    public function agent_audit()
    {
        if(IS_POST)
        {
            $agree = to_int(I("post.agree"));
            $agent_id = to_int(I("post.agent_id"));
            $remark = trim(I("post.remark"));

            if($agree == 1){
                $is_agree = 1;
                $saveData['u_status'] = 1;
            }else{
                $is_agree = 2;
                $saveData['u_status'] = 0;
            }
            $saveData['invitation_code'] = "*";
            // 通过用户名/手机查询是否已添加过改用户
            $agent = M("agent")->where("agent_id = $agent_id")->save($saveData);
            if($agent !== false){
                M("agent_audit")->add(array(
                    'agent_id' => $agent_id,
                    'audit_time' => time(),
                    'audit_manager' => session("manager_id"),
                    'is_agree' => $is_agree,
                    'remark' => $remark
                ));
                $this->success("审核成功" ,U('Agent/index') ,1);
            }else{
                $this->error("审核失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $agent_id = to_int(I('get.id'));
            $agent = D("AgentView")->where("agent.agent_id = $agent_id")->find();
            if(!$agent){
                $this->success("请求失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $this->agent = $agent;
            $this->display();
        }
    }

    // 代理详情
    public function agent_view()
    {
        $agent_id = to_int(I('get.id'));
        $agent = D("AgentView")->where("agent.agent_id = $agent_id")->find();
        if(!$agent){
            $this->success("请求失败" ,$_SERVER['HTTP_REFERER'] ,1);
        }
        $count = M("recommended")->where("add_agent = $agent_id")->count();
        $page = set_page($count, 10);
        $recommend_agents = M("recommended r")
            ->join(C("DB_PREFIX")."agent a ON a.agent_id = r.beadd_agent" ,"LEFT")
            ->where("r.add_agent = $agent_id")->order("r.add_time DESC")
            ->field("r.*,a.agent_name")->limit($page->firstRow.','.$page->listRows)
            ->select();
        $show = $page->show();
        $this->rec_count = $count;
        $this->assign('page',$show);
        $this->assign("recommend_agents" ,$recommend_agents);
        // 代理的品牌
        $brands = M("agent_brand a")
            ->join(C("DB_PREFIX")."brand b ON a.brand_id = b.id" ,"LEFT")
            ->field("a.*,b.b_name")
            ->where("a.agent_id = $agent_id")->select();
        foreach($brands as $b){
            $brand_[] = "<a class='amt' style='height:34px;line-height:34px;'>" .$b["b_name"] ."（". GetRankNameById($b["rank_id"]). "）</a>";
        }
        $agent_brands = implode(" / " ,$brand_);
        $this->assign("agent_brands" ,$agent_brands);
        $agentAddress = M('agent_address')->where( array('agent_id' => $agent_id) )->select();
        $this->assign('agentAddress', $agentAddress);
        $this->agent = $agent;
        $this->display();
    }

    // 代理编辑
    public function edit_agent()
    {
        if(IS_POST)
        {
            $agent_id = to_int(I("post.agent_id"));
            $brand_ids = I("post.brand_id");
            $npwd = trim(I("post.npwd"));
            $to_id = $_POST['to_id'] != '' ? to_int(I("post.to_id")) : '';
            if(!is_array($brand_ids) || empty($brand_ids)){
                $this->error("代理品牌至少选一个" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            // 被修改代理
            if($to_id != 0 && !agent_rank_grade_pk($to_id ,$agent_id) && $to_id != ''){
                $this->error("选择的上级不符合" ,$_SERVER['HTTP_REFERER'] ,2);
            }
            if($to_id != ''){
                $rs = M("agent")->where("agent_id = $agent_id")->save(array("parent_id" => $to_id));
            }
            if($rs !== false){
                // 修改密码
                if($npwd != ""){
                    $salt = M("agent_info")->where("agent_id = %d" ,array($agent_id))->getField("salt");
                    M("agent_info")->where("agent_id = %d" ,array($agent_id))->setField("password" ,md5(md5($npwd) .$salt));
                }
                // 代理品牌更换
                $brands = get_agent_brands( $agent_id);
                foreach($brand_ids as $b_id){
                    // 不在当前代理品牌内 一一添加
                    if(!in_array($b_id ,$brands)){
                        add_agent_brand( $agent_id ,$b_id);
                    }
                }
                // 反向遍历查询已代理的，但是修改却未勾选的
                foreach($brands as $brd){
                    // 不在当前代理品牌内 一一添加
                    if(!in_array($brd ,$brand_ids)){
                        M("agent_brand")->where("agent_id = $agent_id AND brand_id = $brd")->delete();
                    }
                }
                $this->redirect(U('Agent/edit_agent_rank' ,array('id'=> $agent_id)));
            }else{
                $this->error("修改失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $agent_id = to_int(I('get.id'));
            $where['shop_id'] = session("shop_id");
            $agent = D("AgentView")->where("agent.agent_id = %d" ,array($agent_id))->find();
            if(!$agent){
                $this->error("参数错误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $where["status"] = 1;
            $where["agent_brand"] = 1;
            if($agent["parent_id"] != 0){
                $brand_ids = get_agent_brands($agent["parent_id"]);
                $where["id"] = array("in" ,implode("," ,$brand_ids));
            }
            $this->brands = M("brand")->where($where)->select();
            $this->assign("self_brands" ,get_agent_brands( $agent_id) );
            $ranks = M("agent_rank")->where("rank_status = 1")->order("rank_grade ASC")->select();
            $this->assign("ranks" ,$ranks);
            $this->agent = $agent;
            $this->agent_id = $agent_id;
            $this->display();
        }
    }

    // 升级审核中心
    public function upgrade()
    {
        $this->display();
    }

    /*
     * 代理升级机制介绍
     * 不管代理当前属于什么级别，知道是代理升级成功，当前下线代理还是属于自己下线代理，上线代理则更换为升级后级别的上线代理
     * 代理自己也可以添加代理，添加时为自己同等级代理，所属同一上级代理的下线，当自己升级时，自己所添加的所有代理都变成自己的下线代理
     * */
    // 升级审核
    public function audit_up()
    {
        if(IS_POST){
            $up_id = to_int(I("post.up_id"));
            $is_adopt = to_int(I("post.is_adopt"));
            $audit_remark = trim(I("post.remark"));

            $up = D("UpgradeView")->where("agent_upgrade.up_id = $up_id")->find();
            if(!$up){
                $this->error("参数有误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $saveData['is_adopt'] = $is_adopt;
            $saveData['audit_remark'] = $audit_remark;
            $saveData['audit_manager'] = session("manager_id");
            $saveData['audit_time'] = time();
            $rs = M("agent_upgrade")->where("up_id = $up_id")->save($saveData);
            if($rs !== false){
                if($is_adopt == 1){
                    $up_ = M("agent")->where("agent_id = ".$up['agent_id'])->save(array('rank_id' => $up['rank_id']));
                    if($up_ !== false){
                        // 一下两个方法对应微联盟升级机制，重点
                        // 首先更新自己的上级代理
                        update_self_parent_agent( $up['agent_id'] ,$up['rank_id'] , $up['agent_id']);
                        // 更新用户升级后的上下级秩序
                        update_agent_by_upgrade( $up_id );
                    }
                }
                $this->success("审核成功" ,U('Agent/upgrade') ,1);
            }else{
                $this->error("审核失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $up_id = to_int(I('get.id'));
            $upgrade = D("UpgradeView")->where("agent_upgrade.up_id = $up_id")->find();
            if(!$upgrade){
                $this->error("请求失败" ,U("Agent/upgrade"), 1);
            }
            $this->assign('up' , $upgrade);
            $this->display();
        }
    }

    // 代理添加
    public function add_agent()
    {
        if(IS_POST)
        {
            $to_id = to_int(I("post.to_id"));
            $mobile = to_int(I("post.mobile"));
            $c_name = trim(I("post.c_name"));

            if(!is_mobile($mobile)){
                $this->error("手机号码格式有误" ,U('Agent/add_agent') ,1);
            }
            // 通过用户名/手机查询是否已添加过改用户
            $agent = M("agent")->where(array('mobile'=>$mobile,'shop_id'=>session('shop_id')))->find();
            if($agent){
                $this->error("已存在此代理，请仔细核对" ,U('Agent/add_agent') ,1);
            }
            // 查询是否开启注册审核
            $is_audit = M("config")
                ->where("conf_key => 'agent_check' AND conf_type = 'shop'")
                ->getField("conf_value");
            if($is_audit == 1){
                $audit_c = 2;
            }else{
                $audit_c = 1;
            }
            $rs = M("agent")->add(array(
                'agent_name' => $c_name,
                'parent_id' => $to_id,
                'u_status' => $audit_c,
                'mobile' => $mobile,
                'is_agent' => 1,
                'invitation_code' => InvitationCode($mobile ,'ENCODE'),
                'shop_id'=>session('shop_id')
            ));
            if($rs !== false){
                    $id = M("agent")->getLastInsId();
                    $this->redirect(U('Agent/set_rank', array('id' => $id,'to_id'=>$to_id)));
            }else{
                $this->error("添加失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $this->brands = M('brand')->where("`status` = 1 AND `agent_brand` = 1")->select();
            $this->ranks = M('agent_rank')->where("rank_status = 1")->order('rank_grade ASC')->select();
            $this->display();
        }
    }

    // 代理等级设置
    public function set_rank()
    {
        if(IS_POST) {
            $meid = to_int(I("post.meid"));
            $brand_id = I("post.brand_id");
            $rank_id = I("post.rank_id");
            foreach ($brand_id as $k => $val) {
                if (!_int($val)) {
                    $this->error("请求有误", $_SERVER['HTTP_REFERER'], 1);
                }
                $save_data['agent_id'] = $meid;
                $save_data['brand_id'] = $val;
                $save_data['rank_id'] = $rank_id[$k];
                if(!empty($rank_id[$k])) {
                    $req = M('agent_brand')->where(array('agent_id' => $meid, 'brand_id' => $val))->find();
                    if (!$req) {
                        M('agent_brand')->add($save_data);
                    } else {
                        M('agent_brand')->where(array('agent_id' => $meid, 'brand_id' => $val))->save($save_data);
                    }
                }
            }
            $this->success("保存成功" ,U('Agent/index' ) ,1);
        } else {
            $agent_id = to_int(I("get.to_id"));
            $meid = to_int(I("get.id"));
            $rew = M('agent_brand')->where(array('agent_id'=>$meid))->select();

            //????
            if(!empty($rew)){
                $agent_d = new AgentModel();
                $agent_brands = $agent_d->get_agent_brand_and_money($meid);
                // 查询已代理的代理级别
                foreach($agent_brands as $key => $val){
                    $agent_brands[$key]['ranks'] = M("agent_rank")
                        ->where("rank_status = 1 AND brand_id = ".$val['brand_id'])
                        ->order("rank_grade ASC")
                        ->select();
                    $parent_name = GetAgentNameById( $val['parent_agent'] );
                    $agent_brands[$key]['agent_name'] = $parent_name ? $parent_name : "顶级代理";
                }
            }else{
                if (!$agent_id) {
                    $agent_brands = get_agent();
                } else {
                    $agent_brands = get_lowagent($agent_id);
                }
            }
            $this->assign("meid", $meid);
            $this->assign("agent_brands", $agent_brands);
            $this->display();
        }
    }

    // 编辑页代理等级设置
    public function edit_agent_rank()
    {
        if(IS_POST)
        {
            $agent_id = to_int(I("post.agent_id"));
            $brand_id = I("post.brand_id");
            $rank_id = I("post.rank_id");

            if(!is_array($brand_id) || !is_array($rank_id)){
                $this->error("请求有误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            foreach($brand_id as $k => $val){
                if(!_int($val)){
                    $this->error("请求有误" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                M("agent_brand")->where("agent_id = $agent_id AND brand_id = $val")->setField("rank_id" ,$rank_id[$k]);
            }
            $this->success("操作成功" ,U('Agent/index' ) ,1);
        }else{
            $agent_id = to_int(I("get.id"));
            $agent_d = new AgentModel();
            $agent_brands = $agent_d->get_agent_brand_and_money( $agent_id);
            // 查询已代理的代理级别
            foreach($agent_brands as $key => $val){
                $agent_brands[$key]['ranks'] = M("agent_rank")
                    ->where("rank_status = 1 AND brand_id = ".$val['brand_id'])
                    ->order("rank_grade ASC")
                    ->select();
                $parent_name = GetAgentNameById( $val['parent_agent'] );
                $agent_brands[$key]['agent_name'] = $parent_name ? $parent_name : "顶级代理";
            }
            $this->assign("agent_brands" ,$agent_brands);
            $this->assign("agent_id" ,$agent_id);
            $this->display();
        }
    }

    // 代理修改页面搜索
    public function searchAgent()
    {
        if(IS_AJAX)
        {
            $shop_id = session("shop_id");
            $agentName = trim(I('post.aName'));
            if($agentName == ''){ $this->ajaxReturn(array()); }
            $agentList = M("agent")
                ->where("agent_name LIKE '%$agentName%' AND u_status = 1 AND is_agent = 1 AND shop_id = $shop_id")
                ->field("agent_name,agent_id,mobile")
                ->select();
            if($agentList) {
                $this->ajaxReturn($agentList);
            }
        }else{
            exit("error");
        }
    }

    // 代理余额修改
    public function money_edit()
    {
        if(IS_POST){
            $do_type = to_int(I("post.do_type"));
            $amt = to_int(I("post.amt"));
            $agent_id = to_int(I("post.agent_id"));
            if ($do_type == 2) {
                $agent = M("agent")->where("agent_id = %d" ,array($agent_id))->find();
                if ($amt > $agent['money']) {
                    $this->ajaxReturn(array("status" => "err" ,"msg" => '金额有误'));
                }
            }
            $d_type = $do_type == 1 ? "+" : "-";
            $d_con = $do_type == 1 ? "增加" : "减少";
            // 更新预存款
            $tbl = C("DB_PREFIX")."agent";
    		M()->execute("UPDATE $tbl SET `money` = `money` $d_type $amt WHERE agent_id = $agent_id");

            $content = "管理员 " .session('name' ). " 为用户 " .GetAgentNameById($agent_id).
                " $d_con 预存款"."："."$amt 元";
            wlm_write_log($agent_id ,$content ,$amt ,$do_type);

            $this->ajaxReturn(array("status" => "success"));
        }else{
            $agent_id = to_int(I("get.id"));
            $agent = M("agent")->where("agent_id = %d" ,array($agent_id))->find();
            $this->assign("agent" ,$agent);
            $this->display();
        }
    }

    // ajax 读取代理列表
    public function ajax_agent_list()
    {
        $where = 'is_agent = 1 '; // 搜索条件
        $shop_id = session("shop_id");
        $where = "$where AND shop_id = $shop_id";
        $reg = to_int(I('reg'));
        if($reg != 0){
            if($reg == 1){
                $where = "$where AND invitation_code = '*'" ;
            }else{
                $where = "$where AND invitation_code <> '*'" ;
            }
        }
        (I('u_status') !== '') && $where = "$where AND u_status = ".I('u_status') ;
        // 关键词搜索
        $mName = I('mName') ? trim(I('mName')) : '';
        if($mName) $where = "$where AND (agent_name like '%$mName%' or mobile like '%$mName%')" ;
        $count = M('agent')->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $agentList = M('agent')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('agents',$agentList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    // ajax 读取代理升级记录
    public function ajax_up_list()
    {
        $upgrade_d = D("UpgradeView");
        $where = '1 = 1 '; // 搜索条件
        // 关键词搜索
        $mName = I('mName') ? trim(I('mName')) : '';
        if($mName) $where = "$where AND (agent.agent_name like '%$mName%')" ;
        (I('st') != '') && $where = "$where AND agent_upgrade.is_adopt = ". I('st');
        $count = $upgrade_d->where($where)->where(array("shop_id"=>session("shop_id")))->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $upgrades = $upgrade_d->where($where)->where(array('shop_id'=>session("shop_id")))->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('upgrades',$upgrades);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    // 账户资金变动
    public function fund_change()
    {
        $this->display();
    }

    // ajax 读取资金变动列表
    public function ajax_change_list()
    {
        $shop_id = session('shop_id');
        $where = "agent.shop_id = {$shop_id} and agent.is_agent = 1 "; // 搜索条件
        (I('status') !== '') && $where = "$where AND amt_type = ".I('status') ;
        // 关键词搜索
        $user = I('user') ? trim(I('user')) : '';
        $user_ids = array();
        if($user) {
            $us = M("agent")->where("agent_name LIKE '%$user%' AND shop_id = $shop_id AND is_agent = 1")->select();
            if($us){
                foreach($us as $u){
                    $user_ids[] = $u["agent_id"];
                }
                $where = "$where AND amt_change.agent_id IN (".implode("," ,$user_ids).")" ;
            }
        }
        $count = D("AmtAgentView")->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $amt_changes = D("AmtAgentView")->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign("amt_changes" ,$amt_changes);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    // 代理转化普通会员
    public function to_member()
    {
        $agent_id = to_int(I("get.id"));
        M('agent')->where("agent_id = %d" ,array($agent_id))->setField("is_agent" ,2);
        $this->ajaxReturn(array("status" => 'success'));
    }

}